package com.atguigu.gulimall.product.service.impl;

import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {


    @Override
    public List<CategoryEntity> getTreeList() {

        List<CategoryEntity> entities = baseMapper.selectList(null);

        List<CategoryEntity> menuList = entities.stream()
                .filter(category -> category.getParentCid() == 0)
                .map((menu) -> {
                    menu.setChildren(findChildren(menu, entities));
                    return menu;
                })
                .sorted((menu1,menu2) -> {
                    return (menu1.getSort() == null ? 0: menu1.getSort()) -  (menu2.getSort() == null ? 0: menu2.getSort());
                })
                .collect(Collectors.toList());
        return menuList;
    }

    /**
     * 删除分类
     * @param asList
     */
    @Override
    public void removeMenus(List<Long> asList) {
//        TODO 检查当前删除的菜单是否被其他地方引用
        baseMapper.deleteBatchIds(asList);
    }

    private List<CategoryEntity> findChildren(CategoryEntity root, List<CategoryEntity> list) {

        List<CategoryEntity> children = list.stream()
                .filter(cate -> cate.getParentCid() == root.getCatId())
                .map((menu)-> {
                    menu.setChildren(findChildren(menu, list));
                    return menu;
                })
                .sorted((menu1,menu2) -> {
                    return (menu1.getSort() == null ? 0: menu1.getSort()) -  (menu2.getSort() == null ? 0: menu2.getSort());
                })
                .collect(Collectors.toList());

        return children;
    }
}